<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="组id" prop="groupId">
        <el-input
          v-model="queryParams.groupId"
          placeholder="请输入组id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="组名" prop="groupName" v-if="showDept">
        <el-input
          v-model="queryParams.groupName"
          placeholder="请输入组名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="员工id" prop="memberId">
        <el-input
          v-model="queryParams.memberId"
          placeholder="请输入员工id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="员工名" prop="memberName" v-if="showUsers">
        <el-input
          v-model="queryParams.memberName"
          placeholder="请输入员工名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="员工类型id" prop="memberTypeId">
        <el-input
          v-model="queryParams.memberTypeId"
          placeholder="请输入员工类型id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="员工类型名" prop="memberTypeName">
        <el-input
          v-model="queryParams.memberTypeName"
          placeholder="请输入员工类型名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="打卡时间" prop="punchTime">
        <el-date-picker clearable
          v-model="queryParams.punchTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择打卡时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="班次" prop="shift">
        <el-select v-model="queryParams.shift" placeholder="请选择班次" clearable>
          <el-option
            v-for="dict in shift_time"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8" v-if="postGroup==='办公室员工'">
      <el-col :span="1.5">上午：</el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="mini"
          @click="addPunchRecord({
            punchType: '1',
            shift: '1'
          })"
        >上班打卡</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="mini"
          @click="addPunchRecord({
            punchType: '2',
            shift: '1'
          })"
        >下班打卡</el-button>
      </el-col>
      <el-col :span="1.5">下午：</el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="mini"
          @click="addPunchRecord({
            punchType: '1',
            shift: '2'
          })"
        >上班打卡</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="mini"
          @click="addPunchRecord({
            punchType: '2',
            shift: '2'
          })"
        >下班打卡</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['punch:punch:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['punch:punch:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['punch:punch:export']"
        >导出</el-button>
      </el-col> -->
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-row :gutter="10" class="mb8" v-show="roleGroup==='工厂'">
      <template v-for="(item, index) in rosteringList" :key="index">
        <el-col :span="1.5">{{getShiftName(item.shift)}}：</el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            size="mini"
            @click="addPunchRecord({
              punchType: '1',
              shift: item.shift
            })"
          >上班打卡</el-button>
        </el-col>
        <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="mini"
          @click="addPunchRecord({
            punchType: '2',
            shift: item.shift
          })"
        >下班打卡</el-button>
      </el-col>
      </template>
    </el-row>

    <el-table v-loading="loading" :data="punchList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="" align="center" prop="id" /> -->
      <!-- <el-table-column label="组id" align="center" prop="groupId" /> -->
      <el-table-column label="组名" align="center" prop="groupName" />
      <!-- <el-table-column label="员工id" align="center" prop="memberId" /> -->
      <el-table-column label="员工名" align="center" prop="memberName" />
      <!-- <el-table-column label="员工类型id" align="center" prop="memberTypeId" /> -->
      <el-table-column label="员工类型" align="center" prop="memberTypeName" />
      <!-- <el-table-column label="打卡类型id" align="center" prop="punchType" /> -->
      <el-table-column label="打卡时间" align="center" prop="createTime" width="180">
        <!-- <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="班次" align="center" prop="shift" >
        <template #default="scope">
          <dict-tag :options="shift_time" :value="scope.row.shift"/>
        </template>
      </el-table-column>
      <el-table-column label="打卡类型" align="center" prop="punchType" >
        <template #default="scope">
          <dict-tag :options="clock_type" :value="scope.row.punchType"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="打卡状态" align="center" prop="punchStatus" /> -->
      <!-- <el-table-column label="状态" align="center" prop="status" /> -->
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['punch:punch:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['punch:punch:remove']"
          >删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改打卡记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="组id" prop="groupId">
          <el-input v-model="form.groupId" placeholder="请输入组id" />
        </el-form-item>
        <el-form-item label="组名" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入组名" />
        </el-form-item>
        <el-form-item label="员工id" prop="memberId">
          <el-input v-model="form.memberId" placeholder="请输入员工id" />
        </el-form-item>
        <el-form-item label="员工名" prop="memberName">
          <el-input v-model="form.memberName" placeholder="请输入员工名" />
        </el-form-item>
        <el-form-item label="员工类型id" prop="memberTypeId">
          <el-input v-model="form.memberTypeId" placeholder="请输入员工类型id" />
        </el-form-item>
        <el-form-item label="员工类型名" prop="memberTypeName">
          <el-input v-model="form.memberTypeName" placeholder="请输入员工类型名" />
        </el-form-item>
        <el-form-item label="打卡时间" prop="punchTime">
          <el-date-picker clearable
            v-model="form.punchTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择打卡时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPunch, getPunch, delPunch, addPunch, updatePunch } from "@/api/punch/punch";
import { listRostering } from "@/api/rostering/rostering";
import { getUserProfile } from "@/api/system/user";
import { getDicts } from '@/api/system/dict/data'
import { formatDate } from "@/utils" 

export default {
  name: "Punch",
  data() {
    return {
      rosteringList: [],
      clock_type: [],
      shift_time: [],
      showDept: true,
      showUsers: true,
      user: {},
      roleGroup: '',
      postGroup: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 打卡记录表格数据
      punchList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupId: null,
        groupName: null,
        memberId: null,
        memberName: null,
        memberTypeId: null,
        memberTypeName: null,
        punchType: null,
        punchTime: null,
        punchStatus: null,
        status: null,
        shift: null
      },
      queryRosteringParams: {
        pageNum: 1,
        pageSize: 10,
        date: null,
        shift: null,
        groupId: null,
        groupName: null,
        status: null,
        remak: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        groupId: [
          { required: true, message: "组id不能为空", trigger: "blur" }
        ],
        groupName: [
          { required: true, message: "组名不能为空", trigger: "blur" }
        ],
        memberId: [
          { required: true, message: "员工id不能为空", trigger: "blur" }
        ],
        memberName: [
          { required: true, message: "员工名不能为空", trigger: "blur" }
        ],
        memberTypeId: [
          { required: true, message: "员工类型id不能为空", trigger: "blur" }
        ],
        memberTypeName: [
          { required: true, message: "员工类型名不能为空", trigger: "blur" }
        ],
        punchType: [
          { required: true, message: "打卡类型id不能为空", trigger: "change" }
        ],
        punchTime: [
          { required: true, message: "打卡时间不能为空", trigger: "blur" }
        ],
        punchStatus: [
          { required: true, message: "打卡状态不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getUser()
    this.getDicts("shift_time")
    this.getDicts('clock_type')
  },
  methods: {
    getShiftName(id) {
      const data = this.shift_time.find(item => {
        return item.dictValue === id
      })
      if(data) {
        return data.dictLabel
      }
      return id
    },
    // 班次字典
    async getDicts(type) {
      const res = await getDicts(type)
      const data = res.data.map(item => {
        return {
          ...item,
          label: item.dictLabel,
          value: item.dictValue
        }
      })
      this[type] = data
    },
    addPunchRecord({
      punchType,
      shift
    }) {
      const postData = {
        groupId: this.user.dept.deptId,
        groupName: this.user.dept.deptName,
        memberId: this.user.userId,
        memberName: this.user.userName,
        // memberTypeId: null,
        memberTypeName: this.postGroup,
        punchType,
        // punchStatus: null,
        shift,
        punchTime: formatDate(new Date()).split(" ")[0]
      }
      addPunch(postData).then(response => {
        this.$modal.msgSuccess("新增成功");
        this.getList();
      });
    },
    getUser() {
       getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
        if(this.roleGroup==="工厂") {
          this.showDept = false
          this.queryRosteringParams.groupName = this.user.dept.deptName
          this.queryParams.groupName = this.user.dept.deptName
          this.getRosteringList()
        }
        if(this.postGroup === "工厂普通员工"||this.postGroup === "办公室员工") {
          this.queryParams.groupName = this.user.dept.deptName
          this.showDept = false
          this.showUsers =false
          this.queryParams.memberName = this.user.userName
        }
        this.getList();
      });
    },
    /** 查询排班管理列表 */
    getRosteringList() {
      listRostering(this.queryRosteringParams).then(response => {
        this.rosteringList = response.rows.sort((a, b) => (Number(a.shift) - Number(b.shift)));
      });
    },
    /** 查询打卡记录列表 */
    getList() {
      this.loading = true;
      listPunch(this.queryParams).then(response => {
        this.punchList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        groupId: null,
        groupName: null,
        memberId: null,
        memberName: null,
        memberTypeId: null,
        memberTypeName: null,
        punchType: null,
        punchTime: null,
        punchStatus: "0",
        status: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加打卡记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPunch(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改打卡记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePunch(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPunch(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除打卡记录编号为"' + ids + '"的数据项？').then(function() {
        return delPunch(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('punch/punch/export', {
        ...this.queryParams
      }, `punch_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
